package com.taco.springcloud.generate.web.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.taco.springcloud.generate.model.dto.SelectTableDTO;
import com.taco.springcloud.generate.model.dto.GenerateDTO;
import com.taco.springcloud.generate.model.dto.TableDTO;
import com.taco.springcloud.generate.service.GenerateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.DecimalFormat;

/**
 *  在线代码生成器
 *
 *  @author Yu
 *  @date 2019/10/3 16:15
 */
@Api(tags = "在线代码生成器")
@RestController
@RequestMapping("/generate")
@RequiredArgsConstructor
public class GenerateController {

    private final GenerateService generateService;

    @ApiOperation(value = "获取所有表元数据", notes = "获取所有表元数据")
    @GetMapping("/tables/page")
    public HttpEntity<IPage<TableDTO>> tables(@Validated SelectTableDTO selectTableDTO) {
        IPage<TableDTO> result = generateService.selectAll(selectTableDTO.getSchema(), selectTableDTO.getTableName(), selectTableDTO);
        return new HttpEntity<>(result);
    }

    @ApiOperation(value = "代码生成并下载", notes = "代码生成并下载")
    @PostMapping(value = "/execute", produces = "application/octet-stream")
    public HttpEntity execute(@Validated @RequestBody GenerateDTO config) throws Exception{
        String outputDir = System.getProperty("user.dir") + File.separator + "temp" + File.separator + DateUtil.currentSeconds();
        try {
            config.setOutputDir(outputDir);
            generateService.execute(config);

            String fileName = ObjectUtils.defaultIfNull(config.getModuleName(), "code") + ".zip";
            String filePath = outputDir + File.separator + fileName;
            // 获取outputDir下package一级目录（com）
            String srcDir = outputDir + File.separator + (config.getParentPackage().substring(0, config.getParentPackage().indexOf(".")));

            ZipUtil.zip(srcDir, filePath, true);
            download(filePath, fileName);
            return new ResponseEntity(HttpStatus.OK);
        }finally {
            FileUtils.deleteQuietly(new File(outputDir));
        }
    }

    private void download(String filePath, String fileName) throws Exception{
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        try(InputStream is = new FileInputStream(filePath)){
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName  ,"utf-8")+ "");
            response.addHeader("Content-Length", "" + is.available());
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.copy(is, response.getOutputStream());
        }
    }

}
